package com.mediacloud.app.newsmodule.activity;

import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.GroupPhotoDataReciver.PhotoItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.view.BigImageFlingTouchTips;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.user.model.UserInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 组图新闻新样式
 *
 * @author wjj
 */
public class PhotoNewsBigStyleDetailActivity extends StyleSetActivity implements  DataInvokeCallBack<ArticleItemReciver> {
    private ViewPager mViewPager;
    private ArrayList<String> mPhotoUrls = new ArrayList<String>();
    protected List<PhotoItem> photos;
    protected boolean isDisposed;
    NewsDetailInvoker sewsDetailInvoker;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        catalogItem = getIntent().getParcelableExtra("catalog");
        articleItem = getIntent().getParcelableExtra("data");
        if (articleItem == null)
            articleItem = new ArticleItem();
        if (catalogItem == null)
            catalogItem = new CatalogItem();
        sewsDetailInvoker = new NewsDetailInvoker(this);

        initView();
        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
        loadImageNewsDetail();


        decideTitileBarStyle();
        setNewsTitle();

        showStateView(TYPE_LOADING, false);
        onPageStart();
        showPageTransition();


        if (BigImageFlingTouchTips.isFirstOpen(this)) {
            BigImageFlingTouchTips bigImageFlingTouchTips = new BigImageFlingTouchTips(this);
            bigImageFlingTouchTips.show();
        }
    }

    @Override
    protected boolean openTitleBarSetting() {
        return true;
    }







    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    protected void setNewsTitle() {
        int base = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }
    }


    @Override
    protected NavigateBarStyle getNewsDetailNavigateBarStyle() {
        return getAppServerConfigInfo(this).getPhotoNewsBar();
    }

    protected void initView() {
        loadingView = Utility.findViewById(mRootView, R.id.mLoadingView);
        mViewPager = findViewById(R.id.imagePager);
    }

    @Override
    public void showStateView(String type, boolean forceDefault) {
        super.showStateView(type, forceDefault);
        loadingView.bringToFront();
    }


    protected void decideTitileBarStyle() {
        final int mainColor = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getMainColor();
        if (isShowComment(articleItem)) {
            showCommentRelativeView(true);
        } else {
            showCommentRelativeView(false);
        }
    }


    public void loadImageNewsDetail() {
        //现在屏掉直接设置详情 从外面把id给进来的时候    重新去取一次详情  主要是有些搜索的地方要用到

        String navigate_id = catalogItem.getCatid();
        sewsDetailInvoker.getArticleById("" + articleItem.getId(), navigate_id);
    }

    protected void setImages(ArticleItem item) {
        closeStateView();
        try {

            photos = new ArrayList<PhotoItem>();
            JSONArray jsonArray = new JSONArray(item.getImage());

            if (jsonArray.length() == 0) {
                mPhotoUrls.add("");
                PhotoItem photoItem = new PhotoItem();
                photoItem.setImage("");
                photoItem.setThumb("");
                photoItem.setNote("");
                photos.add(photoItem);
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                PhotoItem photoItem = new PhotoItem();
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                String url = jsonObject.optString("src", "");
                String note = jsonObject.optString("info", "");
                String name = jsonObject.optString("name", "");
                photoItem.setImage(url);
                photoItem.setThumb(url);
                photoItem.setNote(note);
                photoItem.setName(name);
                photoItem.setOriginal_src(jsonObject.optString("original_src", url));
                photos.add(photoItem);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mViewPager.setAdapter(new SamplePagerAdapter());
    }




    private class SamplePagerAdapter extends PagerAdapter {
        private int urlsSize;

        public SamplePagerAdapter() {
            urlsSize = photos.size();
        }

        @Override
        public int getCount() {
            return urlsSize;
        }

        @Override
        public View instantiateItem(ViewGroup container, final int position) {
            if (position >= urlsSize) {
                return null;
            }
            View itemView = getLayoutInflater().inflate(R.layout.photonews_touchitem, null);
            ImageView pictureViewX = itemView.findViewById(R.id.image);
            container.addView(itemView, 0);
            pictureViewX.setImageDrawable(AppFactoryGlobalConfig.getDefaultImageLoadDrawable());
            FunKt.load(pictureViewX,photos.get(position).getThumb());
           // GlideUtils.loadUrl(photos.get(position).getThumb(), pictureViewX, null, AppFactoryGlobalConfig.getDefaultImageLoadDrawable());
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (FunKt.isFastClick())
                    PhotoNewsImageItemViewActivity.startActivity(PhotoNewsBigStyleDetailActivity.this, articleItem, catalogItem, photos.get(position).getOriginal_src());
                }
            });
            TextView imageTitle = itemView.findViewById(R.id.imageTitle);
            TextView imageDes = itemView.findViewById(R.id.imageDes);
            imageTitle.setText(photos.get(position).getName());
            imageTitle.getPaint().setFakeBoldText(true);
            String note = photos.get(position).getNote();
            imageDes.setText(note);
            TextView imgPosition = itemView.findViewById(R.id.imgPosition);
            imgPosition.setText((position + 1) + "/" + getCount());
            imgPosition.bringToFront();
            return itemView;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    protected void onDestroy() {
        isDisposed = true;
        if (sewsDetailInvoker != null) {
            sewsDetailInvoker.destory();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        if (photos != null)
            photos.clear();
        sewsDetailInvoker = null;
        super.onDestroy();
        catalogItem = null;
        articleItem = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public int getLayoutResID() {
        return R.layout.activity_photonews_bigstyle;
    }


    protected void intoLogin(Context context) {
        //     ToastUtil.show(context, R.string.please_login);
        LoginUtils.request_source="图片详情";
        LoginUtils.invokeLogin(context);
    }

    @Override
    public void success(ArticleItemReciver data) {
        if (data.state && data.articleItem != null) {
            if (articleItem.getFromComponent() != 1)
                setNewsTitle();
            articleItem = data.articleItem;
            ReportKit.INSTANCE.escalationArticle(articleItem.getId()+"", articleItem.getTitle(),articleItem.getPublishdate(),articleItem.getAddUser());
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            readStatus();
            decideTitileBarStyle();
            AddMedalStatistics.addMedalStatistics(this); //勋章统计
            startAddIntegralCounter();
            setImages(data.articleItem);
        } else {
            fault(null);
        }
    }

    private void startAddIntegralCounter(){
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(PhotoNewsBigStyleDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    @Override
    public void fault(Object data) {
        setImages(new ArticleItem());
        if (null == data) {
            showStateView(TYPE_NO_CONTENT, false);
        } else {
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    public void finish() {
        super.finish();
        ReportKit.INSTANCE.escalationArticleTime();
    }
}